<template>
  <div class="logviewing">
    <!--日志查看 logViewing-->
    <div class="con">
        <div class="leftweb">
            <div class="toptitle">
                <div class="mutitle">webserver日志</div>
                <el-button type="primary" class="last-el-button" @click="webconnectfn">{{weblianjieTitle}}</el-button>
            </div>
            <div class="rightcon" @contextmenu.prevent="showContextMenu(1,$event)">
                <div v-if="contextMenuVisible" class="context-menu"  :style="{ top: contextMenuTop + 'px', left: contextMenuLeft + 'px' }"
                                @click="handleContextMenuClick">
                     <ul>
                           <li @click="switchScrolling(1)">{{zidongflag ? '自动滚动':'手动滚动'}}</li>
                           <li @click="zanting(1)">{{stopFlag ? '继续':'暂停'}}</li>
                           <li @click="qingkong(1)">清空源码</li>
                     </ul>
                 </div>
                 <el-scrollbar style="height:calc(100% - 10px);width: 100%;">
                          <div id="webtargetElement">
                            <div class="conitem" v-for="(item,index) in webleftTable" :key="index">
                                  <div class="texts" v-for="(t,i) in item.msg" :key="i">
                                     <span :style="{'color':t.includes('[error]') ? '#f56c6c' : '#67c23a'}">{{t}}</span>
                                  </div>
                            </div>
                          </div>
                       </el-scrollbar>
            </div>
        </div>
        <div class="righttjx">
            <div class="toptitle">
                <div class="mutitle">通信机主程序日志</div>
                <el-button type="primary" class="last-el-button" @click="txjconnectfn">{{txjlianjieTitle}}</el-button>
            </div>
            <div class="rightcon" @contextmenu.prevent="showContextMenu(2,$event)">
                <div v-if="contextMenuVisible2" class="context-menu"  :style="{ top: contextMenuTop2 + 'px', left: contextMenuLeft2 + 'px' }"
                                @click="handleContextMenuClick">
                     <ul>
                           <li @click="switchScrolling(2)">{{zidongflag ? '自动滚动':'手动滚动'}}</li>
                           <li @click="zanting(2)">{{stopFlag ? '继续':'暂停'}}</li>
                           <li @click="qingkong(2)">清空源码</li>
                     </ul>
                 </div>
                 <el-scrollbar style="height:calc(100% - 10px);width: 100%;">
                          <div id="txjtargetElement">
                            <div class="conitem" v-for="(item,index) in txjleftTable" :key="index">
                                 <div class="texts" v-for="(t,i) in item.msg" :key="i">
                                     <span :style="{'color':t.includes('[error]') ? '#f56c6c' : '#67c23a'}">{{t}}</span>
                                  </div>
                            </div>
                          </div>
                       </el-scrollbar>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
export default {


  data() {
    return {
       weblianjieTitle:"连接",
       weblianjieFlag:false,
       webpanduanFlag:false,
       webws: null,
       webleftTable:[],
       txjleftTable:[],
       txjlianjieTitle:"连接",
       txjlianjieFlag:false,
       txjpanduanFlag:false,
       txjws: null,
       contextMenuVisible: false,
       contextMenuTop: 0,
       contextMenuLeft: 0,
       zidongflag:true,
       stopFlag:false,
       contype:1,//1是webserve，!= 1则是txjmain
       contextMenuVisible2: false,
       contextMenuTop2: 0,
       contextMenuLeft2: 0,
       zidongflag2:true,
       stopFlag2:false,
       newbaseUrl:"",
       webtargetElement:"",
       txjtargetElement:"",
    };
  },

  mounted() {
    var currentUrl = window.location.href;
   var baseUrl = currentUrl.substring(0, currentUrl.indexOf('/#'));
   // 获取端口号
      var port = window.location.port;
      // 去掉端口号
      if (port !== '') {
      baseUrl = baseUrl.replace(':' + port, '');
      }
      // 使用正则表达式去掉开头的'//'
     this.newbaseUrl =  baseUrl.replace(/^(https?:\/\/)/, '');
      this.webtargetElement = document.getElementById('webtargetElement')
      this.txjtargetElement = document.getElementById('txjtargetElement')
  },
  beforeDestroy () {
     if(this.webws){
        this.webdisconnect()
     }
     if(this.txjws){
        this.txjdisconnect()
     }
  },

  methods: {
     showContextMenu(type,event,index) {
        this.contype = type
            if(type == 1){
                this.contextMenuTop = event.layerY;
                this.contextMenuLeft = event.layerX;
                this.contextMenuVisible = true;
            }else {
               this.contextMenuTop2 = event.layerY;
                this.contextMenuLeft2 = event.layerX;
                this.contextMenuVisible2 = true;
            }
            
            window.addEventListener('click', this.hideContextMenu);
     },
     hideContextMenu() {
           if(this.contype == 1){
             this.contextMenuVisible = false;
           }else {
             this.contextMenuVisible2 = false;
           }
            window.removeEventListener('click', this.hideContextMenu);
     },
     handleContextMenuClick(event) {
              event.stopPropagation();
     },
     //切换滚动(type == 1是webserve，!= 1则是txjmain)
    switchScrolling(type,row){
       if(type == 1){
           this.zidongflag = !this.zidongflag
           this.contextMenuVisible = false;
      }else {
          this.zidongflag2 = !this.zidongflag2
             this.contextMenuVisible2 = false;
      }  
    },
    //暂停
    zanting(type,row){
       if(type == 1){
           this.stopFlag = !this.stopFlag
           this.contextMenuVisible = false;
      }else {
          this.stopFlag2 = !this.stopFlag2
             this.contextMenuVisible2 = false;
      }      
    },
    //清空
    qingkong(type,row){
          if(type == 1){
             this.webleftTable = []
             this.contextMenuVisible = false;
          }else {
              this.txjleftTable = []
              this.contextMenuVisible2 = false;
          }      
    },
    //连接
    webconnectfn(){
        if(this.weblianjieFlag){
            return
        }
        if(!this.webpanduanFlag){
              this.webconnect()
        }else {
            this.webdisconnect()
        }
    },
    //连接
    webconnect() {
            // 创建WebSocket连接
            // this.webws = new WebSocket('ws://192.168.1.111:8090/server');
            this.webws = new WebSocket(`ws://${this.newbaseUrl}:8005/server`);
            // 连接打开时的事件
            this.webws.onopen = (event) => {
                // console.log('WebSocket连接已打开：', event);
                this.weblianjieFlag = true // 发送连接请求
                this.weblianjieTitle = '正在连接'
                if(event.type == 'open'){
                    // console.log("成功");
                    this.webpanduanFlag = true
                    this.weblianjieTitle = "断开连接"
                    this.weblianjieFlag = false // 发送连接请求
                    this.$message({showClose: true,message: 'webserve日志连接成功',type: 'success'});
                    this.sendMessage()
                }else {
                    this.weblianjieFlag = false // 发送连接请求
                }
            };
            // 接收到消息时的事件
            this.webws.onmessage = (event) => {
                this.webpanduanFlag = true
                this.weblianjieFlag = false // 发送连接请求
                this.weblianjieTitle = "断开连接"
                if(event.data == 'expectation: [actulValue / monitor / close]'){
                    return
                }
                if(event.data == 'ok'){
                    return
                }
                if(event.data == 'error'){
                    this.$message({showClose: true,message: 'webserve日志通讯异常',type: 'error'});
                    this.disconnect()
                    return
                }
                
                // var resData = JSON.parse(event.data)
                // console.log("拿到的",event.data);
                var chushi = event.data.replace(/\u001b/g, '').replace(/\[31m/g, '').replace(/\[0m/g, '').replace(/\[34m/g, '')
                var result = chushi.split('|||'); // 使用 split 方法分隔字符串
                //判断是否暂停
                if(!this.stopFlag){
                   this.webleftTable.push({
                    msg:result
                   })
                   
                }
                //判断是否自动滚动
                if(this.zidongflag){
                    this.$nextTick(() => {
                      setTimeout(() => {
                             this.webtargetElement.scrollIntoView({ behavior: 'smooth', block: 'end' })
                      },100)
                    })
                      
                }
            };

            // 连接关闭时的事件
            this.webws.onclose = (event) => {
                // console.log('WebSocket连接已关闭：', event);
            };

            // 连接出错时的事件
            this.webws.onerror = (error) => {
                console.error('WebSocket连接出现错误：', error);
            };
    },
     //发送信息
     sendMessage() {
                // 发送消息
                if (this.webws && this.webws.readyState === WebSocket.OPEN) {
                    // 假设我们要发送的参数是一个对象
                    const params = 'webserver_log';
                    // 将对象转换为JSON字符串
                    // const message = JSON.stringify(params);
                    this.webws.send(params);
                    // console.log('发送消息：', params);
                } else {
                    // console.log('WebSocket连接未打开，无法发送消息');
                }
    },
    webdisconnect(){
       // 断开WebSocket连接
                if (this.webws) {
                    const params = 'close';
                    this.webws.send(params);
                    this.webws.close();
                    this.webws = null;
                    this.webpanduanFlag = false
                    this.weblianjieTitle = '连接'
                }
    },
    //连接
    txjconnectfn(){
        if(this.txjlianjieFlag){
            return
        }
        if(!this.txjpanduanFlag){
              this.txjconnect()
        }else {
            this.txjdisconnect()
        }
    },
    txjconnect(){
       // 创建WebSocket连接
            // this.txjws = new WebSocket('ws://192.168.1.111:8091/server');
            this.txjws = new WebSocket(`ws://${this.newbaseUrl}:8005/server`);
            // 连接打开时的事件
            this.txjws.onopen = (event) => {
                // console.log('WebSocket连接已打开：', event);
                this.txjlianjieFlag = true // 发送连接请求
                this.txjlianjieTitle = '正在连接'
                if(event.type == 'open'){
                    // console.log("成功");
                    this.txjlianjieFlag = false // 发送连接请求
                    this.txjpanduanFlag = true
                    this.txjlianjieTitle = "断开连接"
                    this.$message({showClose: true,message: '通信机主程序连接成功',type: 'success'});
                    this.sendMessage2()
                }else {
                    this.txjlianjieFlag = false // 发送连接请求
                }
            };
            // 接收到消息时的事件
            this.txjws.onmessage = (event) => {
                this.txjpanduanFlag = true
                this.txjlianjieFlag = false // 发送连接请求
                this.txjlianjieTitle = "断开连接"
                if(event.data == 'expectation: [actulValue / monitor / close]'){
                    return
                }
                if(event.data == 'ok'){
                    return
                }
                if(event.data == 'error'){
                    this.$message({showClose: true,message: '通信机主程序通讯异常',type: 'error'});
                    this.disconnect()
                    return
                }
                
                // var resData = JSON.parse(event.data)
                // console.log("resData",event.data);
                var chushi = event.data.replace(/\u001b/g, '').replace(/\[31m/g, '').replace(/\[0m/g, '').replace(/\[34m/g, '')
                var result = chushi.split('|||'); // 使用 split 方法分隔字符串
                   
                //判断是否暂停
                if(!this.stopFlag){
                   this.txjleftTable.push({
                    msg:result
                   })
                   
                }
                
                //判断是否自动滚动
                if(this.zidongflag){
                  this.$nextTick(() => {
                      setTimeout(() => {
                             this.txjtargetElement.scrollIntoView({ behavior: 'smooth', block: 'end' })
                      },100)
                    })
                      
                }
            };

            // 连接关闭时的事件
            this.txjws.onclose = (event) => {
                // console.log('WebSocket连接已关闭：', event);
            };

            // 连接出错时的事件
            this.txjws.onerror = (error) => {
                console.error('WebSocket连接出现错误：', error);
            };
    },
    //发送信息
     sendMessage2() {
                // 发送消息
                if (this.txjws && this.txjws.readyState === WebSocket.OPEN) {
                    // 假设我们要发送的参数是一个对象
                    const params = 'txjmain_log';
                    // 将对象转换为JSON字符串
                    // const message = JSON.stringify(params);
                    this.txjws.send(params);
                    // console.log('发送消息：', params);
                } else {
                    // console.log('WebSocket连接未打开，无法发送消息');
                }
    },
    txjdisconnect(){
        // 断开WebSocket连接
                if (this.txjws) {
                    const params = 'close';
                    this.txjws.send(params);
                    this.txjws.close();
                    this.txjws = null;
                    this.txjpanduanFlag = false
                    this.txjlianjieTitle = '连接'
                }
    },
    
  },
};
</script>
<style lang="scss" scoped>
    .logviewing {
      width: 100%;
      height: 100%;
      .con {
         width: 100%;
         height: 100%;
        //  background-color: #fff;
         display: flex;
         .rightcon {
           width: 100%;
           height: calc(100% - 55px);
           background-color: #1A1A1A;
           border-radius: 4px;
           padding: 20px 0px;
           box-sizing: border-box;
           color: #fff;
           font-size: 14px;
           position: relative;
           :deep(.el-scrollbar__thumb) {
                       background-color:#52779a;
                     }
                     :deep(.el-scrollbar__view) {
                         white-space: wrap;
                     }
         }
         // 右键菜单
            .context-menu {
            position: absolute;
            background-color: white;
            border: 1px solid #ccc;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            }

            .context-menu ul {
            list-style: none;
            padding: 0;
            margin: 0;
            }

            .context-menu li {
                color: #1A1A1A;
                padding: 8px 16px;
                cursor: pointer;
            }

            .context-menu li:hover {
            background-color: #dedede;
            }
            .conitem {
                    width: 100%;
                    //    height: 30px;
                    padding:12px;
                    box-sizing: border-box;
                    border-bottom: 1px dashed #515151;
                    //    margin-bottom: 15px;
                    .texts {
                           user-select: text;
                           word-wrap: break-word; /* 允许长单词换行 */
                           span {
                              user-select: text;
                              word-wrap: break-word; /* 允许长单词换行 */
                           }
               }
            }
         .toptitle {
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-bottom: 12px;
              padding-bottom: 6px;
              border-bottom: 1px solid #ccc;
              .mutitle {
                 font-size: 14px;
              }
           }
         .leftweb {
           width: calc(50% - 6px);
           height: 100%;
           margin-right: 12px;
           background-color: #fff;
           padding: 12px;
           box-sizing: border-box;
           
         }
         .righttjx {
           width: calc(50% - 6px);
           height: 100%;
           background-color: #fff;
           padding: 12px;
           box-sizing: border-box;
         }
      }
          
    }
</style>